// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-22 23:29
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.BrainTrick;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

@SuppressWarnings("ALL")
public class Convert {
    /*-----z字型变换-----*/
    public String convertT(String s, int numRows) {
        // 现将给定字符串转化为z字形，然后从左到右进行遍历
        // 观察规律得出题解，除了第一列和最后一列可以超过一个字符，其他列都只有一个字符
        // 可以向正向创建z字符阵，然后纵向读取

        int n = s.length();
        if (n < 2 || numRows < 2) {
            return s;
        }
        int k = 0, col = ((n / (numRows + (numRows - 2))) + 1) * (n - 2) + 1;
        char[][] res = new char[numRows][col];
        here:
        for (int j = 0; j < col; j++) {
            if (j % (numRows - 1) == 0) {
                for (int i = 0; i < numRows; i++) {
                    // 完整行

                    res[i][j] = s.charAt(k++);
                    if (k > n - 1) {
                        break here;
                    }
                }
            } else {
                if (k > n - 1) {
                    break here;
                }
                res[numRows - (j % (numRows - 1)) - 1][j] = s.charAt(k++);
            }
        }
        // 纵向遍历
        StringBuilder builder = new StringBuilder();
        for (char[] re : res) {
            for (char c : re) {
                if (Character.isAlphabetic(c) || c == ',' || c == '.') {
                    builder.append(c);
                }
            }
        }
        return builder.toString();
    }


    static int N = 1010;
    static char[][] g = new char[N][N];
    static int[] idxs = new int[N];

    public String convert(String s, int m) {
        if (m == 1) {
            return s;
        }
        int n = s.length();
        Arrays.fill(idxs, 0);
        for (int i = 0, j = 0, k = 1; i < n; i++) {
            /*-----精妙的循环控制-----*/
            g[j][idxs[j]++] = s.charAt(i);
            j += k;
            if (j < 0) {
                j += 2;
                k = 1;
            } else if (j == m) {
                j -= 2;
                k = -1;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < idxs[i]; j++) {
                sb.append(g[i][j]);
            }
        }
        return sb.toString();
    }

    @Test
    public void shout() {
        // String test = "PAYPALISHIRING";
        String test = "ABCD";
        int numRows = 3;
//        String test = "ABCDE";
//        int numRows = 4;
//        String test = "AB";
//        int numRows = 2;
        System.out.println(convertT(test, numRows));
    }

}
